package nbcp.db

import nbcp.base.comm.ApiResult
import nbcp.base.comm.SystemContext

import nbcp.base.extend.*
import nbcp.base.minus
import nbcp.base.utils.Md5Util
import nbcp.db.mongo.*
import nbcp.db.mongo.entity.AdminUser
import nbcp.db.mongo.table.*
import nbcp.web.LoginUser
import java.time.LocalDateTime
import javax.servlet.http.HttpServletRequest

/**
 * Created by udi on 17-5-23.
 */


/**
 * 登录验证，返回错误消息
 */
fun AdminGroup.AdminUserEntity.doLogin(loginName: String, password: String, request: HttpServletRequest): ApiResult<AdminUser> {

    var loginUser = mor.admin.adminLoginUser.query()
            .where { it.loginName match loginName }
            .toEntity();

    if (loginUser == null) {
        return ApiResult("找不到用户：" + loginName);
    }

    if (loginUser.errorLoginTimes > 10 && (LocalDateTime.now() - loginUser.lastLoginAt).totalMinutes < 5) {
        return ApiResult("帐户频繁登录失败，已被锁定5分钟！")
    }

    var user = mor.admin.adminUser.query()
            .where { it.loginName match loginName }
            .toEntity()

    if (user == null) {
        return ApiResult("找不到用户：" + loginName)
    }


    if (loginUser.password != Md5Util.getBase64Md5(password)) {

        mor.admin.adminLoginUser.update()
                .set { it.lastLoginAt to LocalDateTime.now() }
                .set { it.errorLoginTimes to (loginUser.errorLoginTimes + 1) }
                .where { it.loginName match loginName }
                .exec();
        return ApiResult("密码错误")
    }

    mor.admin.adminLoginUser.update()
            .set { it.lastLoginAt to LocalDateTime.now() }
            .set { it.errorLoginTimes to 0 }
            .where { it.loginName match loginName }
            .exec();

    var loginUserModel = LoginUserModel(user.id,user.loginName, user.name,user.token);
    request.LoginUser = loginUserModel
    request.session.setAttribute(SystemContext.loginSessionKey,loginUserModel)
    request.session.LoginUserIsAdmin = true;

    return ApiResult.of(user!!)
}


